﻿// JScript File


//*************************病虫害监测******************
function createRSIndexDiv_Disease(modeltype)
{
    if(MAP_TYPE == "IMSMAPONLY" || MAP_TYPE == "IMSLEGEND" || MAP_TYPE == "IMSMAP")
    {
        useModel = "false";
        swift2GMap();
        $("#infoTable").empty();
        click_count=0;
        switchImg();
    }
    
    var divSelections = document.createElement("div");
    var divImages =  document.createElement("div");
    var divContent = document.createElement("div");
    var divCustomIndex_disease = document.createElement("div");
    
    var txtProvince = document.createTextNode("省（市、自治区）");
    var txtCounty = document.createTextNode("县（市、区）");
    var txtYear = document.createTextNode("年");
    
    var sltProvince = document.createElement("select");
    sltProvince.id = "sltProvince";
    var sltCounty = document.createElement("select");
    sltCounty.id = "sltCounty";
    var sltYear = document.createElement("select");
    sltYear.id = "sltYear";
    
    var thisDate = new Date();
    var thisYear = thisDate.getFullYear();
    for(var i = 0; i < 10; i++)
    {
        var yearOption = document.createElement("option");
        yearOption.value = thisYear - i;
        yearOption.text = thisYear - i;
        sltYear.options.add(yearOption);
    }
    
    
    if (parseInt(USER_DISTRICT_ID) == 0 )
    {
        var ProvinceOptionText = new Array("北京","河北","吉林","黑龙江","江苏","山东","河南","湖南","浙江","新疆");
        var ProvinceOptionValue = new Array("1","5","9","10","11","16","17","19","12","31");
        var ProvinceOptions  = createOptions(ProvinceOptionValue,ProvinceOptionText);
        for(var i = 0; i < ProvinceOptionText.length; i++)
        {
            sltProvince.options.add(ProvinceOptions[i]);
        }
        fillCountySelect();
        $(sltProvince).bind("change",fillCountySelect);
        $(sltCounty).bind("change",function(){
            var pid= $(sltCounty).val();
                
            $.get("Services/getDistrictList.aspx",{DISTID:pid,TEMP:Math.random()},function(data){
                var xmlDocument = data.documentElement;
                var nodes = xmlDocument.getElementsByTagName("District");             
                var lat = nodes[0].attributes[2].nodeValue;
                var lng = nodes[0].attributes[3].nodeValue;
                var centerPoint = new GLatLng(lat, lng);
                gmap.setCenter(centerPoint, 9);
            
            });
        });
    }
    else
    {
        if (parseInt(USER_DISTRICT_ID) == 1 )
        {
            
            var countyOptionText = new Array("全省（市、区）","大兴","通州","顺义","昌平","密云","平谷","怀柔","延庆","房山","丰台","门头沟","石景山","海淀","朝阳","中心四城区");
            var countyOptionValue = new Array("1","74","71","72","73","78","76","75","77","70","66","69","67","68","65","61");
            var countyOptions  = createOptions(countyOptionValue,countyOptionText);
            for(var i = 0; i < countyOptions.length; i++)
            {
                    sltCounty.options.add(countyOptions[i]);
            }            
        }
        else if(parseInt(USER_DISTRICT_ID) < 50)
        {
            //待修改，采用异步方式获得所有子节点及自己
            strUrl = "Services/getDistrictList.aspx";
            $.get(strUrl,{DISTID:USER_DISTRICT_ID,
                          TEMP:Math.random()
                          },
                          function(data){
                              var xmlDocument = data.documentElement;
                              var nDistricts = xmlDocument.childNodes.length;
                              var countyOptionText = new Array();
                              var countyOptionValue = new Array();
                              for(var i = 0; i < nDistricts; i++)
                              {
                                countyOptionText[i] = xmlDocument.childNodes[i].attributes[1].nodeValue;
                                countyOptionValue[i] = xmlDocument.childNodes[i].attributes[0].nodeValue;
                              }
                              var countyOptions  = createOptions(countyOptionValue,countyOptionText);
                              for(var i = 0; i < countyOptions.length; i++)
                              {
                                  sltCounty.options.add(countyOptions[i]);
                              }
                                                            
                          });
        
        }
        else
        {
            var countyOptionText = new Array(USER_DISTRICT_NAME);
            var countyOptionValue = new Array(USER_DISTRICT_ID);
            var countyOptions  = createOptions(countyOptionValue,countyOptionText);
            for(var i = 0; i < countyOptions.length; i++)
            {
                    sltCounty.options.add(countyOptions[i]);
            }            
        }
    }    

    
    var btnGetImageList = document.createElement("input");
    btnGetImageList.type = "button";
    btnGetImageList.value = "查询影像列表";
    
    //为获取遥感影像列表button绑定点击时间
    $(btnGetImageList).bind("click",function(){
        
        swift2GMap(); //用于对不同地区同一灾害监测的IMS地图清除
       
        var selectedLocation = sltCounty.value;
        var selectedyear = sltYear.value;

        var strURL = "services/getImageList.aspx";
        
        //执行按钮点击后的事件，查找image list并生成元素
        $.get(strURL,{LOC:selectedLocation,YEAR:selectedyear,tmp:Math.random()},function(data){
            var xmlDocument = data.documentElement;
            var nImages = xmlDocument.childNodes.length;
            var nodes = xmlDocument.getElementsByTagName("Image");  
            var number = nodes.length; 
            if (number == 0) 
            {
                $(divImages).empty();
                alert("没有符合条件的影像数据！");
                return;
            }                            
           
            var imageId = new Array();
            var imageName = new Array();
            var BrowserType = getBrowserType();
            if(BrowserType == "MSIE")
            {                             
                for (var i = 0; i < nImages; i++)
                {
                    imageId[i] = xmlDocument.childNodes[i].attributes[0].nodeValue;
                    imageName[i] = xmlDocument.childNodes[i].attributes[1].nodeValue;
                }
            }
            else
            {
                for (var i = 0; i < (nImages -1)/2; i++)
                {
                    imageId[i] = xmlDocument.childNodes[i * 2 + 1].attributes[0].nodeValue;
                    imageName[i] = xmlDocument.childNodes[i * 2 + 1].attributes[1].nodeValue;
                }
            }
            var sltImageList = document.createElement("select");
            sltImageList.id = "ImageListSelect";                           
                        
            var ImageOptions = createOptions(imageId,imageName);
            for (var i = 0; i < ImageOptions.length; i++)
            {
                sltImageList.options.add(ImageOptions[i]);
            } 
                  
            $(sltImageList).bind("change",getImageType);                      
            
            //灾害监测模块添加判断--病虫害 
            if(modeltype=="Disease")
            {
                //====================================================
                //增加样点block大小选择
                var sltBlockSizeList = document.createElement("select");
                sltBlockSizeList.id = "BlockSizeSelect";
                var blockSizeOptionsId = new Array("size1","size3","size5");
                var blockSizeOptionsName = new Array("1 × 1","3 × 3","5 × 5");

                var BlockSizeOptions = createOptions(blockSizeOptionsId,blockSizeOptionsName);
                for (var i = 0; i < BlockSizeOptions.length; i++)
                {
                    sltBlockSizeList.options.add(BlockSizeOptions[i]);
                }
                //===================================================
                
                var btnOpenSamplePoints_disease = document.createElement("input");
                btnOpenSamplePoints_disease.type = "button";
                btnOpenSamplePoints_disease.value = "查看样点文件";
                $(btnOpenSamplePoints_disease).bind("click",loadSamplePointsTable_disease);
                

                var btnGetIndex_disease = document.createElement("input");
                btnGetIndex_disease.type = "button";
                btnGetIndex_disease.value = "提取植被指数";
                
                $(btnGetIndex_disease).bind("click",calculateRSIndex_disease);
                
                //==========================================================
                //增加自定义植被指数计算功能
                    
                    var btnSetCustomIndex_disease = document.createElement("input");
                    btnSetCustomIndex_disease.type = "button";
                    btnSetCustomIndex_disease.value = "设置自定义植被指数";
                    //$(btnGetIndex).bind("click",{fileName:$(sltImageList).val()},calculateRSIndex);
                    $(btnSetCustomIndex_disease).bind("click",function(){
                        
                        $(btnGetIndex_disease).attr("disabled",true)
                        
                        var txtCustomIndexFormula = document.createTextNode("请输入自定义植被指数表达式（格式参考ENVI的band math要求）：");
                        var CustomIndexTextBoxName = new Array("CustomIndexText");
                        var CustomIndexTextBox = createTexts(CustomIndexTextBoxName);
                        $(CustomIndexTextBox).width(330);
                        
                        var txtBandlist = document.createTextNode("请输入波段列表（以,分割，如4,3,2表示使用了4、3、2三个波段）：");
                        var BandlistTextBoxName = new Array("BandListText");
                        var BandlistTextBox = createTexts(BandlistTextBoxName);
                        $(BandlistTextBox).width(330);
                        
                        
                        var btnGetCustomIndex = document.createElement("input");
                        btnGetCustomIndex.type = "button";
                        btnGetCustomIndex.value = "提取植被指数";
                        $(btnGetCustomIndex).bind("click",calculateCustomRSIndex); 
                        
                        var btnCancelCustomIndex = document.createElement("input");
                        btnCancelCustomIndex.type = "button";
                        btnCancelCustomIndex.value = "放弃提取自定义植被指数";
                        $(btnCancelCustomIndex).bind("click",function(){
                            $(btnGetIndex_disease).attr("disabled",false)
                            with($(divCustomIndex_disease)) {
                                css("margin-top","0px");
                                css("border","solid 0px black")
                                empty();
                            }
                        });   
                        
                    with($(divCustomIndex_disease)) {
                        css("margin-top","10px");
                        css("border","solid 1px black")
                        empty();
                        append(txtCustomIndexFormula);
                        append("<br/>");
                        append(CustomIndexTextBox);
                        append("<br/>");

                        append(txtBandlist);
                        append("<br/>");
                        append(BandlistTextBox);
                        append("<br/>");

                        append(btnGetCustomIndex);
                        append(btnCancelCustomIndex);
                    }          
                
                });
                 
                with($(divImages)){                              
                    css("margin-top","10px");
                    css("border","solid 1px black")                
                    empty();
                    append(sltImageList);
                    append("<br/>");
                    append(btnOpenSamplePoints_disease);
                    append("<br/>");
                    append(sltBlockSizeList);
                    append(btnGetIndex_disease);
         //           append(btnSetCustomIndex_disease)
         //           append(divCustomIndex_disease)
                  }
                  
                getImageType();
           }
           //灾害监测模块添加判断--干旱 
           if(modeltype=="Drought")
           {
                var btnOpenSamplePoints_disease = document.createElement("input");
                btnOpenSamplePoints_disease.type = "button";
                btnOpenSamplePoints_disease.value = "查看样点文件";
                $(btnOpenSamplePoints_disease).bind("click",loadSamplePointsTable_drought);
                
                //====================================================
                //增加样点block大小选择
                var sltBlockSizeList = document.createElement("select");
                sltBlockSizeList.id = "BlockSizeSelect";
                var blockSizeOptionsId = new Array("size1","size3","size5");
                var blockSizeOptionsName = new Array("1 × 1","3 × 3","5 × 5");

                var BlockSizeOptions = createOptions(blockSizeOptionsId,blockSizeOptionsName);
                for (var i = 0; i < BlockSizeOptions.length; i++)
                {
                    sltBlockSizeList.options.add(BlockSizeOptions[i]);
                }
                //提取植被指数
                var btnGetIndex_disease = document.createElement("input");
                btnGetIndex_disease.type = "button";
                btnGetIndex_disease.value = "提取植被指数";
                //$(btnGetIndex_disease).css("background-color", "#FFEEEE");
                //btnGetIndex_disease.style.backgroundColor="red";
                $(btnGetIndex_disease).bind("click",calculateRSIndex_Drought);
                //===================================================
                
                with($(divImages)){                              
                    css("margin-top","10px");
                    css("border","solid 1px black")
              //      height("100");               
                    empty();
                    append(sltImageList);
                    append(btnOpenSamplePoints_disease);
                    append("<br/>");
                    append(sltBlockSizeList);
                    append(btnGetIndex_disease);
                  }
           }
           modelType = modeltype;
           $("#forDatacache").data("calculateType",modelType);//存入当前操作的类型，以备在创建模型时判断
                    
        });
    });
    
    
    with($(divSelections)){
        if(parseInt(USER_DISTRICT_ID)==0)
        {
            append(sltProvince);
            append(txtProvince);
        }
        append(sltCounty);
        append(txtCounty);
        append("<br/>");
        append(sltYear);
        append(txtYear);
        append("<br/>");
        append(btnGetImageList);
        
    }
    
    with($(divContent)){
//        css("min-height",180);
        append(divSelections);
        append(divImages);
//        height(260);
//        css("overflow","scroll");
    }
    
    return divContent;
}  

function createParamRelateDiv_Disease()
{
    var divContent = document.createElement("div"); 
    divContent.id =  "divtable";
    
    //定义表格的列名称
    var txtAgriTitle = document.createTextNode("农学参数");
    var txtRSIndexTitle = document.createTextNode("植被指数");

    var txtAgriArray = new Array( "病虫害指数(DI)","","","","","","","","","","","","","");                             
    
    //创建农学参数的textnode数组                                
    var txtNodeAgriArray = createTextNode(txtAgriArray);                                
    
    var txtChkAgriArray = new Array("chkDiseaseIndex","","","","","","","","","","","","","");
    //定义农学参数的CheckBox数组                                
    var chkAgriArray = createCheckboxs(txtChkAgriArray);     
    
    //将名称与checkbox连接成span元素
    var spanAgriArray = new Array();
    for(var i = 0; i < txtChkAgriArray.length; i++)
    {
        spanAgriArray[i] = document.createElement("span");
        spanAgriArray[i].appendChild(chkAgriArray[i]);
        spanAgriArray[i].appendChild(txtNodeAgriArray[i]);
    }
    //定义植被指数名称列表
    var txtRSIndexArray = new Array("NDWI(叶面缺水指数)", "TVI(三角形植被指数)", "NDVI(归一化植被指数)", "NSI(Non-such Index)", "WI(温暖指数)", "NDGI(归一化差异绿度指数)", "GEMI(全球环境监测指数)","EVI(增强植被指数)","RVI(比值植被指数)","ARVI(大气阻抗植被指数)","SAVI(土壤调整植被指数)","MSAVI(改进调整植被指数)","DVI(差值植被指数)","RDVI(重归一化植被指数)");
    
    //创建植被指数的textnode数组       
    var txtNodeRSIndexArray = createTextNode(txtRSIndexArray);                                
    
    //定义植被指数的CheckBox ID列表
    var txtChkRSIndexArray = new Array("chkNDWI", "chkTVI", "chkNDVI", "chkNSI", "chkWI", "chkNDGI", "chkGEMI", "chkEVI","chkRVI","chkARVI","chkSAVI","chkMSAVI","chkDVI","chkRDVI");
    
    //定义植被指数的CheckBox数组                                
    var chkRSIndexArray = createCheckboxs(txtChkRSIndexArray); 
    
    //将名称与checkbox连接成span元素
    var spanRSIndexArray = new Array();
    for(var i = 0; i < txtRSIndexArray.length; i++)
    {
        spanRSIndexArray[i] = document.createElement("span");
        spanRSIndexArray[i].appendChild(chkRSIndexArray[i]);
        spanRSIndexArray[i].appendChild(txtNodeRSIndexArray[i]);
    }
    //创建绘制地图的button元素
    var btnCalcuRxy = document.createElement("input");
    btnCalcuRxy.type = "button";
    btnCalcuRxy.value = "计算相关系数";
    $(btnCalcuRxy).bind("click",function(){
        var selectedAgriParams = "";
        var selectedRSIndex = "";
        for(var i = 0; i < chkRSIndexArray.length; i++)
        {
            if(chkAgriArray[i].checked == true)
            {
                selectedAgriParams += chkAgriArray[i].id.substring(3) + ",";
            }
            if(chkRSIndexArray[i].checked == true)
            {
                selectedRSIndex += chkRSIndexArray[i].id.substring(3) + ",";
            }

        }
        if(selectedAgriParams.length == 0) {alert("您没有选择农学参数，请您先选择至少一项农学参数！");return;}
        if(selectedRSIndex.length == 0) {alert("您没有选择植被指数，请您先选择至少一项植被指数！");return;}
        selectedAgriParams = selectedAgriParams.substring(0,selectedAgriParams.length - 1);
        selectedRSIndex = selectedRSIndex.substring(0,selectedRSIndex.length - 1);
        
        var imageId = $("#ImageListSelect").val();
        if(typeof(imageId)=="undefined") {alert("您没有选择用于建模的遥感影像，请您先从上一组菜单中选择一幅遥感影像！");return;}
        
        calculateRelatedCoefficient_Disease(selectedAgriParams,selectedRSIndex,"disease");
    
    });    

    //将上面生成的元素组织成表格形式
    var paramTableTitle = new Array(txtAgriTitle,txtRSIndexTitle);
    var paramTableValue = new Array(spanAgriArray,spanRSIndexArray);
    var paramTable = new DataTable(paramTableTitle,paramTableValue,2);
    
    
    //将表格和button添加到div
    with($(divContent)){
        append(paramTable);
        append(btnCalcuRxy);
//        css("min-height",180);
//        height(335);
//        css("overflow","scroll");
    }

    return divContent;

}

//********************筛选敏感农学参数与旱情指数****************
function createParamRelateDiv_Drought()
{
    var divContent = document.createElement("div");
    //定义表格的列名称
    var txtAgriTitle = document.createTextNode("农学参数");
    var txtRSIndexTitle = document.createTextNode("干旱指数");
     
    //定义农学参数名称                                   
    var txtAgriArray = new Array("土壤含水量(0-5cm)","土壤含水量(10-20cm)","土壤含水量(20-30cm)","");
    var txtNodeAgriArray = createTextNode(txtAgriArray);                                                                
    
    //定义农学参数的CheckBox ID列表
    var txtChkAgriArray = new Array("chkSoilWater0_5","chkSoilWater10_20","chkSoilWater20_30","");   
    //定义农学参数的CheckBox数组                                
    var chkAgriArray = createCheckboxs(txtChkAgriArray); 
    
    //将名称与checkbox连接成span元素
    var spanAgriArray = new Array();
    for(var i = 0; i < txtChkAgriArray.length; i++)
    {
        spanAgriArray[i] = document.createElement("span");
        spanAgriArray[i].appendChild(chkAgriArray[i]);
        spanAgriArray[i].appendChild(txtNodeAgriArray[i]);
    } 
                                   
    ///////////////////////////////////////////////////
    //定义植被指数名称列表
    var txtRSIndexArray = new Array("叶面缺水指数（NDWI）", "短红外垂直失水指数（SPSI）", "温度植被干旱指数（TVDI）", "植被供水指数法（VSWI）");
    
    //创建植被指数的textnode数组       
    var txtNodeRSIndexArray = createTextNode(txtRSIndexArray);                                
    
    //定义植被指数的CheckBox ID列表
    var txtChkRSIndexArray = new Array("chkNDWI", "chkSPSI", "chkTVDI", "chkVSWI");
    
    //定义植被指数的CheckBox数组                                
    var chkRSIndexArray = createCheckboxs(txtChkRSIndexArray); 
    
    //将名称与checkbox连接成span元素
    var spanRSIndexArray = new Array();
    for(var i = 0; i < txtRSIndexArray.length; i++)
    {
        spanRSIndexArray[i] = document.createElement("span");
        spanRSIndexArray[i].appendChild(chkRSIndexArray[i]);
        spanRSIndexArray[i].appendChild(txtNodeRSIndexArray[i]);
    }
    
    //创建绘制地图的button元素 用于计算相关系数
    var btnCalcuRxy = document.createElement("input");
    btnCalcuRxy.type = "button";
    btnCalcuRxy.value = "计算相关系数";
    
    
    
    $(btnCalcuRxy).bind("click",function(){
        var selectedAgriParams = "";
        var selectedRSIndex = "";
        
        for(var i = 0; i < chkRSIndexArray.length; i++)
        {
            if(chkAgriArray[i].checked == true)
            {
                selectedAgriParams += chkAgriArray[i].id.substring(3) + ",";
            }
            if(chkRSIndexArray[i].checked == true)
            {
                selectedRSIndex += chkRSIndexArray[i].id.substring(3) + ",";
            }
        }
        if(selectedAgriParams.length == 0) {alert("您没有选择农学参数，请您先选择至少一项农学参数！");return;}
        if(selectedRSIndex.length == 0) {alert("您没有选择植被指数，请您先选择至少一项植被指数！");return;}
        selectedAgriParams = selectedAgriParams.substring(0,selectedAgriParams.length - 1);
        selectedRSIndex = selectedRSIndex.substring(0,selectedRSIndex.length - 1);
        
        var imageId = $("#ImageListSelect").val();
        if(typeof(imageId)=="undefined") {alert("您没有选择用于建模的遥感影像，请您先从上一组菜单中选择一幅遥感影像！");return;}
        
        calculateRelatedCoefficient(selectedAgriParams,selectedRSIndex,"drought");//此方法增加参数，以确定要显示的列头
    
    });
    
    //利用已有模型进行计算，不计算相关系数
    var btnUseModelCal = document.createElement("input");
    btnUseModelCal.type = "button";
    btnUseModelCal.value = "利用已有模型计算";
    
    $(btnUseModelCal).bind("click",function(){
        
        useModel = "true";
        
        select_Argiparam = "";
        select_RSindex = "";
        var checkedAgri = 0;
        var checkedRsindex = 0;
        for(var i = 0; i < chkRSIndexArray.length; i++)
        {
            if(chkAgriArray[i].checked == true)
            {
                select_Argiparam += chkAgriArray[i].id.substring(3) + ",";
                checkedAgri += 1;
            }
            if(chkRSIndexArray[i].checked == true)
            {
                select_RSindex += chkRSIndexArray[i].id.substring(3) + ",";
                checkedRsindex += 1;
            }
        }
        
        var imageId = $("#ImageListSelect").val();
        if(typeof(imageId)=="undefined") {alert("您没有选择用于建模的遥感影像，请您先从上一组菜单中选择一幅遥感影像！");return;}
        if(select_Argiparam.length == 0) {alert("您没有选择农学参数，请您先选择至少一项农学参数！");return;}
        if(select_RSindex.length == 0) {alert("您没有选择植被指数，请您先选择至少一项植被指数！");return;}
        if(checkedAgri > 1){alert("利用已有模型进行计算，只需选择一项农学参数！");return;}
        if(checkedRsindex > 1){alert("利用已有模型进行计算，只需选择一项植被指数！");return;}
        else {alert("请在下一步建立监测模型时选择--导入已有模型！");}
              
    });
    
    //将上面生成的元素组织成表格形式
    var paramTableTitle = new Array(txtAgriTitle,txtRSIndexTitle);
    var paramTableValue = new Array(spanAgriArray,spanRSIndexArray);
    var paramTable = new DataTable(paramTableTitle,paramTableValue,2);
    
    //将表格和button添加到div
    with($(divContent)){      
        append(paramTable);
        append(btnCalcuRxy);
        append("&nbsp;");
        append("&nbsp;");
        append("&nbsp;");
        append(btnUseModelCal);
//        css("min-height",180);
        height(240);
//        css("overflow","scroll");
    }

    return divContent;   
}


//*************************************建立监测模型***********************
function createModelSelectDiv_Disease(modeltype)
{
    var divContent = document.createElement("div");

    var txtModelName = document.createTextNode("模型名称");
    var txtModelEquation = document.createTextNode("模型方程");
    var txtModelR_Squared =  document.createTextNode("拟合优度");
    var txtModelSelect =  document.createTextNode("选择模型");
    
    var txtLine = document.createTextNode("线性模型");
    var txtExp = document.createTextNode("指数模型");
    var txtLn = document.createTextNode("对数模型");
    
    var txtTitleNames = new Array(txtLine,txtExp,txtLn);

    //创建模型选择的radio元素
    var modelRadioNameArray = new Array("radioLine","radioExp","radioLn");
    
    var modelRradioArray = new Array();
    modelRradioArray = createRadios(modelRadioNameArray,"ModelRadio",radioCheckModel);
    

    //空文本串
    var txtBlank = document.createTextNode("");

    //记录模型方程的文本框
    var txtTextNameArray = new Array("txtLine","txtExp","txtLn");
    var txtTextArray = new Array();
    txtTextArray = createTexts(txtTextNameArray);
    
    //记录拟合优度的文本框
    txtTextNameArray = new Array("txtLineR","txtExpR","txtLnR");
    var txtRArray = new Array();
    txtRArray = createTexts(txtTextNameArray);
    
    for(var i = 0; i < txtTextArray.length; i++)
    {
        $(txtTextArray[i]).bind("change",{elem:$(txtTextArray[i]).attr("id")},function(event){
            alert("该处仅用于显示计算结果，不能接受任何数据输入！");       
            eval($('#' + event.data.elem)).val("");
        });
        
        $(txtRArray[i]).bind("change",{elem:$(txtRArray[i]).attr("id")},function(event){
            alert("该处仅用于显示计算结果，不能接受任何数据输入！");
            eval($('#' + event.data.elem)).val("");
        });
    }
    
    //创建计算模型的button元素
    var calcuButtonNameArray = new Array("计算");
    calcuButtonArray = createButtons(calcuButtonNameArray,"");
     
    /////////////////////////////////////// 添加灾害类型判断
    if(modeltype == "Drought")
    {
        $(calcuButtonArray).bind("click",resolveModelParam);
    }
    if(modeltype == "Disease")
    {
        $(calcuButtonArray).bind("click",resolveModelParam_Disease);
    }
    
    
    ///////////////////////////////////////添加导入、保存模型功能
    var cdtdiv=document.createElement("div");
    var inputBut=document.createElement("input");
    inputBut.type="button";
    inputBut.id="inputBut";
    inputBut.value="导入已有模型";
    var cancelBut=document.createElement("input");
    cancelBut.type="button";
    cancelBut.id="cancelBut";
    cancelBut.value="没有合适的模型"; 
   
    $(inputBut).bind("click",function(){        
        var sltTime=document.createElement("select");
        sltTime.id="sltImagetime";
        var sltMType=document.createElement("select");
        sltMType.id="sltModelType";
        var inBut=document.createElement("input");
        $(inputBut).attr("disabled",true);
        $(cancelBut).attr("disabled",false);
        inBut.type="button";
        inBut.value="导入选择的模型";       
    $(cancelBut).bind("click",function(){
        $(inputBut).attr("disabled",false);
        $(cancelBut).attr("disabled",true);
        $(cdtdiv).empty();
        $(cdtdiv).css("margin-top","0px");
    });         
        
        var distId = "";
        if($("#sltCounty").val()==1)  distId = $("#sltProvince").val();            
        else  distId = $("#sltCounty").val();
        var time = $("#sltYear").val();      
        
        var strURL="services/getImageList.aspx";
        $.get(strURL,{DISTID:distId,TIME:time},function(data){
            var xmlDocument = data.documentElement;
            var nImages = xmlDocument.childNodes.length;
            var nodes = xmlDocument.getElementsByTagName("Image");  
            var number = nodes.length;
            if (number == 0) 
            {
                alert("没有与您选择地区相对应的模型数据！");
                return;
            }
            var imageId = new Array();
            var imageName = new Array();
            var BrowserType = getBrowserType();
            if(BrowserType == "MSIE")
            {
                for (var i = 0; i < nImages; i++)
                {
                    imageId[i] = xmlDocument.childNodes[i].attributes[0].nodeValue +'-'+ xmlDocument.childNodes[i].attributes[2].nodeValue;
                    imageName[i] = xmlDocument.childNodes[i].attributes[1].nodeValue;
                }
            }
            else
            {
                for (var i = 0; i < (nImages -1)/2; i++)
                {
                    imageId[i] = xmlDocument.childNodes[i * 2 + 1].attributes[0].nodeValue +'-'+ xmlDocument.childNodes[i * 2 + 1].attributes[2].nodeValue;
                    imageName[i] = xmlDocument.childNodes[i * 2 + 1].attributes[1].nodeValue;
                }
            }
            var ImageOptions = createOptions(imageId,imageName);
            for (var i = 0; i < ImageOptions.length; i++)
            {
                sltTime.options.add(ImageOptions[i]);
            }
        });
        var MtypeOptionText=new Array("1","2","3","4");
        var MtypeOptionValue=new Array("全 部","线 性","指 数","对 数");
        var MtypeOptions=createOptions(MtypeOptionText,MtypeOptionValue);
        for(var i=0;i<MtypeOptions.length;i++)
        {
            sltMType.options.add(MtypeOptions[i]);        
        }
        $(sltMType).css("width","80px");
        var handlUrl="Services/getInfoForModle.aspx";
        $(inBut).bind("click",function(){
            var _dist="";
            var _date="";
            var _typeid="";
            var x_y="";            
            if($("#sltImagetime"))
            {
                var temp=$("#sltImagetime").val();
                var tempArr=temp.split('-');
                var reg=/\d/;
                var i_start=tempArr[0].search(reg);
                _date=tempArr[0].substring(i_start,tempArr[0].length);
                _dist=tempArr[1];
            }
            _typeid=$("#sltModelType").val();
           
           //对选择的植被指数与农学参数进行判断，是利用相关系数计算的结果还是直接利用已有模型
           var x_y_radio = "";
           if(useModel == "true")
           {
                x_y = select_Argiparam.split(',',1) + "-" + select_RSindex.split(',',1);
             //   useModel == "false";
           }
           else
           {
               x_y_radio=$("#infoTable input[type='radio']");
                if(x_y_radio){
                    for(var i=0;i<x_y_radio.length;i++)
                    {
                        if($(x_y_radio[i]).attr("checked")==true)
                        {
                            x_y=$(x_y_radio[i]).attr("id");
                            break;
                        }
                    }
                }
            }
            if(!x_y) {alert("您还没有选择用于反算模型的农学参数—植被指数序列，请您在下方的表格中选取！若您是利用已有模型进行计算，可导入已有模型！");return;}
            $.getJSON(handlUrl,{DIST:_dist,DATE:_date,TYPE:_typeid,X_Y:x_y,TMP:Math.random()},function(json){
                  switch(_typeid)
                  {
                     default:
                     case "1":
                          if(json.L_Coefficient < 0)
                          { $("#txtLine").val("Y = "+json.L_Intercept+""+json.L_Coefficient+"*X"); }
                          else
                          { $("#txtLine").val("Y = "+json.L_Intercept+"+"+json.L_Coefficient+"*X");  }                           
                          $("#txtLineR").val(json.L_Goodness);
                          if(json.E_Coefficient < 0)
                          { $("#txtExp").val("Y = "+json.E_Intercept+""+json.E_Coefficient+"*Exp(X)"); }
                          else
                          { $("#txtExp").val("Y = "+json.E_Intercept+"+"+json.E_Coefficient+"*Exp(X)"); }                             
                          $("#txtExpR").val(json.E_Goodness);
                          if(json.Lo_Coefficient < 0)
                          { $("#txtLn").val("Y = "+json.Lo_Intercept+""+json.Lo_Coefficient+"*Ln(X)"); }
                          else
                          { $("#txtLn").val("Y = "+json.Lo_Intercept+"+"+json.Lo_Coefficient+"*Ln(X)"); }
                          $("#txtLnR").val(json.Lo_Goodness); 
                          break;
                     case "2":
                          if(json.Coefficient < 0)
                          { $("#txtLine").val("Y = "+json.Intercept+""+json.Coefficient+"*X"); }
                          else
                          { $("#txtLine").val("Y = "+json.Intercept+"+"+json.Coefficient+"*X");  }                           
                          $("#txtLineR").val(json.Goodness); 
                          $("#txtExp").val("");
                          $("#txtExpR").val("");
                          $("#txtLn").val("");
                          $("#txtLnR").val("");
                          break;
                     case "3":
                          if(json.Coefficient < 0)
                          { $("#txtExp").val("Y = "+json.Intercept+""+json.Coefficient+"*Exp(X)"); }
                          else
                          { $("#txtExp").val("Y = "+json.Intercept+"+"+json.Coefficient+"*Exp(X)"); }                             
                          $("#txtExpR").val(json.Goodness); 
                          $("#txtLine").val("");
                          $("#txtLineR").val("");
                          $("#txtLn").val("");
                          $("#txtLnR").val("");
                          break;
                     case "4":
                     //     $("#txtLn").val("Y= "+json.Intercept+"+ ("+json.Coefficient+")X");   
                          if(json.Coefficient < 0)
                          { $("#txtLn").val("Y = "+json.Intercept+""+json.Coefficient+"*Ln(X)"); }
                          else
                          { $("#txtLn").val("Y = "+json.Intercept+"+"+json.Coefficient+"*Ln(X)"); }
                          $("#txtLnR").val(json.Goodness); 
                          $("#txtLine").val("");
                          $("#txtLineR").val("");
                          $("#txtExp").val("");
                          $("#txtExpR").val("");
                          break;
                  }                    
            });
            
        });
        with($(cdtdiv))
        {
             css("margin-top","10px");
             css("border","solid 1px black");                
             empty();
             append(sltTime);
             append("&nbsp;");
             append("&nbsp;");
             //append(sltDist);
             append("&nbsp;");
             append("&nbsp;");
             append(sltMType);
             append("<br />");
             append("<br />");
             append("&nbsp;");
             append("&nbsp;");
             append("&nbsp;");
             append("&nbsp;");
             append("&nbsp;");
             append("&nbsp;");
             append("&nbsp;");
             append("&nbsp;");
             append("&nbsp;");
             append("&nbsp;");
             append("&nbsp;");
             append(inBut);
             append(cancelBut);
        }
    });
    
    //绑定导入方法,此处应该添加用户权限
    var saveBut=document.createElement("input");
    saveBut.type="button";
    saveBut.id="saveBut";
    saveBut.value="保存模型";
    var _user_roleindex=USER_ROLE_INDEX;
    $.getJSON("Services/getRolepurview.aspx",{RI:_user_roleindex},function(json){
        if(json.worktype==1) saveBut.style.visibility=hidden;        
    });
    var _model=""; 
    if(arguments[0]) _model=arguments[0];
    else _model="0";
    $(saveBut).bind("click",function(){
        var _dist="";
        var _rootid="";
        var _date="";
        var _typename="";
              
        var _intercept="";
        var _coefficient="";
        var _goodness="";
        var x_y="";
        _rootid=USER_ROOTID;

        if($("#sltCounty").val()==1)  _dist=$("#sltProvince").val();            
        else  _dist=$("#sltCounty").val();
        if($("#ImageListSelect")) 
        {
            _date=$("#ImageListSelect").val();
            var reg=/\d/;
            var i_start=_date.search(reg);
            _date=_date.substring(i_start,_date.length);
        }else
        {
            _date="2009-01-01";
        }
        var _radio=$("input[name='ModelRadio']");
        var _equation="";
        if(_radio)
        {
            for(var i=0;i<_radio.length;i++)
            {
                if($(_radio[i]).attr("checked")==true)
                {
                    switch($(_radio[i]).attr("id"))
                    {
                        case "radioLine" : 
                              _goodness=$("#txtLineR").val();
                              _equation=$("#txtLine").val();
                              _typename="linear";
                              break;
                        case "radioExp": 
                              _goodness=$("#txtExpR").val();
                              _equation=$("#txtExp").val();
                              _typename="exp";
                              break;
                        case "radioLn" : 
                              _goodness=$("#txtLnR").val();
                              _equation=$("#txtLn").val();
                              _typename="log";
                              break;
                    }
                    break;
                }
            }
            if(_equation.length == 0)
            {
                alert("请选择需要保存模型的名称！");
                return;
            }
        }
        var e_array=_equation.split('=');
        var _e_array ="";
        var index = e_array[1].indexOf("+");
        if(index == -1)
        {
            _e_array = e_array[1].split('-');
            _intercept=_e_array[0];
            _coefficient = parseFloat(_e_array[1].split('*')[0]);
            _coefficient = -_coefficient;
        }
        else
        {
            _e_array = e_array[1].split('+');
            _intercept=_e_array[0];
            _coefficient = parseFloat(_e_array[1].split('*')[0]);
        }
//        var _e_array=e_array[1].split('-');
//        _intercept=_e_array[0];
//        var _reg=/\d/;
//        var _ii=_e_array[1].search(_reg);
//        var _iii=_e_array[1].search(/\)/);
//        _coefficient=_e_array[1].substring(_ii,_iii);
        var x_y_radio=$("#infoTable input[type='radio']");
        if(x_y_radio){
            for(var i=0;i<x_y_radio.length;i++)
            {
                if($(x_y_radio[i]).attr("checked")==true)
                {
                    x_y=$(x_y_radio[i]).attr("id");
                    break;
                }
            }
        }
        if(!x_y) {alert("您还没有选择用于反算模型的农学参数—植被指数序列，请您在下方的表格中选取！");return;}
        var strURL_save="Services/saveModel.aspx";
        $.getJSON(strURL_save,{DSIT:_dist,DATE:_date,TNAME:_typename,INTERCEPT:_intercept,COE:_coefficient,GN:_goodness,XY:x_y,RID:_rootid,ML:_model,TMP:Math.random()},
                 function(json){
                         if(json.result=="2") alert("模型已存在，请重新选择要保存的模型！");
                         else {
                            if(json.result) alert("模型保存成功！");
                            else alert("模型保存失败！");
                         }
            
        });
    });
    
    var modelTableTitle = new Array(txtModelName,txtModelEquation,txtModelR_Squared,txtModelSelect);

    var modelTableValueAll = new Array(txtTitleNames,txtTextArray,txtRArray,modelRradioArray);
    var modelTable = new DataTable(modelTableTitle,modelTableValueAll,2);


    with($(divContent))
    {
        append(modelTable);
        append(calcuButtonArray);
        append("&nbsp;");
        append(saveBut);
        append("&nbsp;");
        append(inputBut);
        append(cdtdiv);
    }
    
    return divContent;

}

//********************灾害监测绘图********************
function createDrawGrowingGraphDiv_Disease(modeltype)
{
    if(arguments.length > 0)
    {
        layerName = arguments[0];
    }
    else
    {
        layerName = "旱情分级";
    }
    
    var divGraduations = document.createElement("div");
    var divButtons = document.createElement("div");
    var divContent = document.createElement("div");
 
    var txtClassNumber = document.createElement("input");
    txtClassNumber.type = "text";
    txtClassNumber.width = "72";
    txtClassNumber.id = "classNumber";
    
    //设置一个隐藏文本框来记录分级设置的级别数
    var hiddenTextNumber = document.createElement("input");
    hiddenTextNumber.id = "GraduationNumber";
    hiddenTextNumber.type = "hidden";
    hiddenTextNumber.value = 0;

    
    //创建绘制地图的button元素
    var btnClassify = document.createElement("input");
    btnClassify.type = "button";
    btnClassify.value = "设置分级刻度";
    $(btnClassify).bind("click",function(){
        //待添加处理用户权限的处理
        var classNumber = txtClassNumber.value;
        if(classNumber.length == 0 || classNumber == "0") 
        {
            $(divGraduations).empty();
            $(txtClassNumber).val("");

            //alert("请在左侧文本框中填写分级刻度数！");
            return;
        }
        else if(classNumber == "1")
        {
            alert("分级刻度数至少应该大于等于2！");
            return;
        }
        var txtGraduationValueNames = new Array();
        var txtGraduationLabelNames = new Array();
        var txtGraduationColorNames = new Array();
        var baseText1 = "Graduation";
        var baseText2 = "Label";
        var baseText3 = "Color"
        for(var i = 0;i < classNumber;i++)
        {
            txtGraduationValueNames[i] = baseText1 + i;
            txtGraduationLabelNames[i] = baseText2 + i;
            txtGraduationColorNames[i] = baseText3 + i;
        }
        
        var txtGraduationValues = new Array();
        txtGraduationValues = createTexts(txtGraduationValueNames);
        
        var txtGraduationLabels = new Array();
        txtGraduationLabels = createTexts(txtGraduationLabelNames);
        
        var txtGraduationColors = new Array();
        txtGraduationColors = createTexts(txtGraduationColorNames);
        
        for(var i = 0; i < txtGraduationValues.length; i++)
        {
            $(txtGraduationValues[i]).width(120);
            $(txtGraduationLabels[i]).width(120);
            $(txtGraduationColors[i]).width(120);
        }
               
        
        var ColorIndex = 1;
        for(var i = 0; i < txtGraduationColors.length; i++)
        {
            $(txtGraduationColors[i]).bind("click",{id:i},function(event){
                ColorIndex = event.data.id;
            });
            
            $(txtGraduationColors[i]).ColorPicker({
	            onSubmit: function(hsb, hex, rgb) {
		            eval($('#Color' + ColorIndex)).val(hex);		            
	            },
	            onBeforeShow: function () {
		            $(this).ColorPickerSetColor(this.value);
	            }
            });
        }
        
         //////////////////////////////////////增加灾害类型判断
        if(modeltype=="Disease")
        {
            var tableTitleString = new Array("病情指数刻度(数字)","病害状况描述（文字）","颜色设置");
            var tableTitles = createTextNode(tableTitleString);
        }
        if(modeltype=="Drought")
        {
            var tableTitleString = new Array("旱情参数刻度(数字)","干旱状况描述（文字）","颜色设置");
            var tableTitles = createTextNode(tableTitleString);
        }
        
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        //定义设置默认选项的title列表
        var txtDefaultControl = new Array(" 默认值", " 默认值", " 默认值");
        
        //创建默认选项的textnode数组       
        var txtDefaultControlArray = createTextNode(txtDefaultControl);                                

        //定义设置默认选项的CheckBox ID列表
        var txtChkDefaultControlArray = new Array("defGraduations", "defLabels", "defColors");
        
        //定义设置默认选项的CheckBox数组                                
        var chkDefaultControlArray = createCheckboxs(txtChkDefaultControlArray); 
        
        for(var i = 0; i < chkDefaultControlArray.length; i++)
        {
            $(chkDefaultControlArray[i]).bind("click",function(){
                if($("#defGraduations").attr("checked") == true)
                {
                    for(var j = 0; j < txtGraduationValues.length; j++)
                    {
                        $(txtGraduationValues[j]).attr("disabled",true);// = true;
                    }
                }
                else
                {
                    for(var j = 0; j < txtGraduationValues.length; j++)
                    {
                        $(txtGraduationValues[j]).attr("disabled",false);// = false;
                    }
                }
                
                if($("#defLabels").attr("checked") == true)
                {
                    for(var j = 0; j < txtGraduationValues.length; j++)
                    {
                        $(txtGraduationLabels[j]).attr("disabled",true);// = true;
                    }
                }
                else
                {
                    for(var j = 0; j < txtGraduationValues.length; j++)
                    {
                        $(txtGraduationLabels[j]).attr("disabled",false);// = false;
                    }
                }
                if($("#defColors").attr("checked") == true)
                {
                    for(var j = 0; j < txtGraduationValues.length; j++)
                    {
                        $(txtGraduationColors[j]).attr("disabled",true);// = true;
                    }
                }
                else
                {
                    for(var j = 0; j < txtGraduationValues.length; j++)
                    {
                        $(txtGraduationColors[j]).attr("disabled",false);// = false;
                    }
                }

            });        
        }
        
        var tableTitles2 = new Array();
        for (var i = 0; i < 3; i++)
        {
            tableTitles2[i] = document.createElement("span");
            with($(tableTitles2[i]))
            {
                append(tableTitles[i]);
                append("<br/>");

                append(chkDefaultControlArray[i]);
                append(txtDefaultControlArray[i]);
            }
            //tableTitles2[i].style.width = "120px";
        }   
                
             
        var tableValue = new Array(txtGraduationValues,txtGraduationLabels,txtGraduationColors);
        
        var table = new DataTable(tableTitles2,tableValue, 2);
              

        hiddenTextNumber.value = classNumber;
        
        $(divGraduations).empty();
        divGraduations.appendChild(table);
        divGraduations.appendChild(hiddenTextNumber);
    });


    ///////////////////////////////////////增加灾害类型判断 lb090409
    //创建绘制地图的button元素
    if(modeltype=="Disease")
    {
        var btnDraw = document.createElement("input");
        btnDraw.type = "button";
        btnDraw.value = "绘制病害分级图";
        $(btnDraw).bind("click",{flag:"IMSMAP"},getIMSMap_Disease);
    }
    if(modeltype=="Drought")
    {
        var btnDraw = document.createElement("input");
        btnDraw.type = "button";
        btnDraw.value = "绘制干旱分级图";
        $(btnDraw).bind("click",{flag:"IMSMAP"},getIMSMap);
    }
    
    if(USER_ROLE_INDEX.indexOf("0002") == -1)
    {
        divButtons.appendChild(btnDraw);
    }
    else
    {
        divButtons.appendChild(txtClassNumber);
        divButtons.appendChild(btnClassify);
        divButtons.appendChild(btnDraw);
    }

    with($(divContent))
    {
        append(divButtons);
        append(divGraduations);
    }
    
    return divContent;
    
}


